<?php


namespace app\home\controller;
use app\home\model\Admin as AdminModel;

use think\Controller;
use think\Request;
use think\Validate;

class Login extends Controller
{
    protected $adminModel;
    public function __construct(AdminModel $adminModel)
    {
        parent::__construct();
        $this->adminModel = $adminModel;
    }

    public function login(){
        //判断是否已登录
        if(session('user_id')){
            return redirect(url('index'));
        }
        return $this->fetch();
    }

    public function doLogin(Request $request){
        $username = $request->param('username');
        $password = $request->param('password');

        $validate = Validate::make([
            'username|用户名' => 'require',
            'password|密码' => 'require'
        ]);

        $data = [
            'username'  => $username,
            'password' => $password
        ];

        if (!$validate->check($data)) {
            return json($validate->getError());
        }

        $where = [
            'username' => $username,
            'password' => md5($password)
        ];
        $user = $this->adminModel->where($where)->find();
        $back = [
            'status' => 200,
            'msg' => '登陆成功'
        ];
        if($user){
            session('user_id',$user->id);
        }else{
            $back['status'] = 301;
            $back['msg'] = '账号密码错误';
        }

        return json($back);
    }

    public function logout(){
        session('user_id', null);
    }
}